package com.maxverse.boot.web2image.queue.handler;

import com.maxverse.boot.web2image.queue.consumer.TaskConsumer;
import com.maxverse.boot.web2image.common.model.TaskMessage;
import com.maxverse.boot.web2image.common.service.TaskProcessService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

@Slf4j
@Component
public class TaskHandler {
    private final ExecutorService executorService;
    private final TaskConsumer taskConsumer;
    private final TaskProcessService taskProcessService;
    
    public TaskHandler(
            @Autowired TaskConsumer taskConsumer,
            @Autowired TaskProcessService taskProcessService) {
        this.taskConsumer = taskConsumer;
        this.taskProcessService = taskProcessService;
        this.executorService = Executors.newFixedThreadPool(5); // 可配置的线程池大小
    }
    
    @Scheduled(fixedDelay = 1000) // 每秒检查一次队列
    public void handleTasks() {
        TaskMessage task = taskConsumer.receiveTask();
        if (task != null) {
            executorService.submit(() -> {
                try {
                    taskProcessService.processTask(task);
                } catch (Exception e) {
                    log.error("Failed to process task: {}", task.getTaskId(), e);
                }
            });
        }
    }
} 